﻿#include "logger.h"
#include <QDir>
#include <QDate>
#include <QTime>

QString ColorTextStr(QString content, quint8 color = TextBlack)
{
    return QString("<font color=%1>%2</font>").arg(TextColorMap.value(color)).arg(content);
};

void Logger::run()
{
    running = true;
    QString fileName = logFileName;
    if(!logFilePath.isEmpty())
    {
        fileName = logFilePath + "/" + logFileName;
    }
    QFile file(fileName);
    while(running)
    {
        QString logData = "";
        if(logQueue.size() > 0)
        {
            if(file.open(QIODevice::Append))
            {
                while(logQueue.size() > 0)
                {
                    QTextStream stream(&file);
                    {
                        QMutexLocker locker(&logMutex);
                        logData = logQueue.dequeue();
                    }
                    stream<<QTime::currentTime().toString("hh:mm:ss ")<<logData<<Qt::endl;
                }
                file.close();
            }
            else
            {
                emit err_occur("open file failed.");
            }
        }
        else
        {
            this->msleep(500);
        }
    }
}

void Logger::Info(const QString &msg)
{
    qtinfo<<msg;
    emit log_msg(ColorTextStr("Info:" + msg));
    if(running)
    {
        QMutexLocker locker(&logMutex);
        logQueue.enqueue(msg);
    }
}

void Logger::Bingo(const QString &msg)
{
    qtinfo<<msg;
    emit log_msg(ColorTextStr("Info:" + msg, TextGreen));
    if(running)
    {
        QMutexLocker locker(&logMutex);
        logQueue.enqueue(msg);
    }
}

void Logger::Critical(const QString &msg)
{
    qtcritical<<msg;
    emit log_msg(ColorTextStr("Info:" + msg, TextBlue));
    if(running)
    {
        QMutexLocker locker(&logMutex);
        logQueue.enqueue(msg);
    }
}

void Logger::Warning(const QString &msg)
{
    qtwarning<<msg;
    emit log_msg(ColorTextStr("Info:" + msg, TextOrange));
    if(running)
    {
        QMutexLocker locker(&logMutex);
        logQueue.enqueue(msg);
    }
}

void Logger::Error(const QString &msg)
{
    qtwarning<<msg;
    emit log_msg(ColorTextStr("Info:" + msg, TextRed));
    if(running)
    {
        QMutexLocker locker(&logMutex);
        logQueue.enqueue(msg);
    }
}

QString Logger::getLogFileName() const
{
    return logFileName;
}

void Logger::setLogFileName(const QString &newLogFileName)
{
    logFileName = newLogFileName;
}

QString Logger::getLogFilePath() const
{
    return logFilePath;
}

bool Logger::setLogFilePath(const QString &newLogFilePath)
{
    QDir dir(newLogFilePath);
    if(dir.exists())
    {
        logFilePath = dir.absolutePath();
        return true;
    }
    emit err_occur("path is not exist.");
    return false;
}
